package com.freesaas.merchant.action;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fast.common.exception.FastException;
import com.fast.common.http.HttpTransport;
import com.freesaas.merchant.util.PubDataUtil;
import com.freesaas.merchant.util.WechatUtil;

@Controller
public class P001Action {

	private Logger logger = LoggerFactory.getLogger(P001Action.class);

	/**
	 * 重定向为了获取token code的值
	 * @param txAmt
	 * @param mercid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/P00101/{mercid}")
	public ModelAndView P00101(String txAmt, @PathVariable("mercid") String mercid, HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
		logger.info("浏览器信息：{}", userAgent);
		logger.info("请求IP：{}", request.getRemoteAddr());
		return new ModelAndView("redirect:" + WechatUtil.getRedirectUrl(mercid));
	}

	/**
	 * 获取openId的值
	 * @param code
	 * @param state
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/P00102")
	public ModelAndView P00102(String code, String state, HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
		logger.info("浏览器信息：{}", userAgent);
		Map<String, String> data = new HashMap<String, String>();
		try {
			String ret = HttpTransport.httpGet(WechatUtil.getOpenIdUrl(code));
			Map<String, String> retmap = JSON.parseObject(ret, new TypeReference<Map<String, String>>() {
			});
			String openId = retmap.get("openid");
			if (StringUtils.isBlank(openId)) {
				throw new IllegalArgumentException("授权码不合法");
			}
			data.put("openId", openId);
			data.put("mercId", state);
			data.put("mercOrdNo", PubDataUtil.getJrnNo());
		} catch (FastException e) {
			logger.error("", e);
		}
		return new ModelAndView("pay_input", data);
	}
}
